package com.jinlejia.bbs.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatButton;

/**
 * @author 王进 on 2019/3/20.
 */

public class RecordButton extends AppCompatButton {
    //region construction
    public RecordButton(Context context) {
        this(context,null);
    }

    public RecordButton(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public RecordButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    //endregion
    private RecordActionListener listener;

    private boolean touchEnable = true;

    public void setTouchEnable(boolean touchEnable) {
        this.touchEnable = touchEnable;
    }

    public void setRecordActionListener(RecordActionListener listener) {
        this.listener = listener;
    }
    private boolean isRecording = false;
    private boolean cancel = true;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.performClick();
        int action = event.getAction();
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isRecording = true;
                cancel = false;
                setText("松开  发送");
                if (listener!=null)
                    listener.onStartRecorder();
                break;
            case MotionEvent.ACTION_MOVE:
                if (isRecording){
                    if(wantToCancel(x,y)){
                        cancel = true;
                        setText("手指上划，取消发送");
                    }else {
                        cancel = false;
                        setText("松开  发送");
                    }
                    if (listener!=null && touchEnable){
                        listener.onCancelRecorder(cancel);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                setText("按住  说话");
                if (listener!=null && touchEnable){
                    listener.onStopRecorder(cancel);
                }
                break;
        }
        return true;
    }

    private boolean wantToCancel(int x, int y){
        //如果左右滑出 button
        if (x < 0 || x > getWidth()) {
            return true;
        }
        //如果上下滑出 button  加上我们自定义的距离
        if (y < -50 || y > getHeight() + 50) {
            return true;
        }
        return false;
    }

    public interface RecordActionListener{
        void onStartRecorder();
        void onStopRecorder(boolean cancel);
        void onCancelRecorder(boolean cancel);
    }
}
